/*
文章管理 对应模块
其中 编辑文章 函数未使用
*/

package model

import (
    "fmt"
    "strings"
    "time"

    "gitee.com/keeving/quanta-test-cat/utils/errmsg"
    "github.com/gin-gonic/gin"
    "gorm.io/gorm"
)

type Article struct {
    // Category Category `gorm:"foreignkey:Cid"`    // 关联分类
    gorm.Model   
    ID           uint      `gorm:"primary_key;auto_increment" json:"id"`
    CreatedAt    time.Time `json:"createTime"`
    UserID       uint      `json:"userid"`
    Title        string    `gorm:"type:varchar(100);not null" json:"title"`
    Cid          int       `gorm:"type:int;not null" json:"cid"`
    Desc         string    `gorm:"type:varchar(200)" json:"desc"`
    Content      string    `gorm:"type:longtext" json:"content"`
    Img          string    `gorm:"type:text" json:"imgs"`
    CommentCount int       `gorm:"type:int;not null;default:0" json:"commentNum"`
    ReadCount    int       `gorm:"type:int;not null;default:0" json:"readNum"`
    LikeCount    int       `gorm:"type:int;not null;default:0" json:"likeNum"`
}

// CreateArt 新增文章
func CreateArt(data *Article) int {
    err := db.Create(&data).Error
    if err != nil {
        return errmsg.ERROR
    }
    return errmsg.SUCCESS
}

// TODO: 创建个函数，将 GetCateArt 等函数，要查询的文章基本信息，通过传入 aid 直接返回

// GetCateArt 查询分类下的所有文章
func GetCateArt(id int, pageSize int, pageNum int) ([]gin.H, int, int64) {
    var cateArtList []Article
    var total int64

    // 计算总记录数
    err := db.Model(&Article{}).Where("cid = ?", id).Count(&total).Error
    if err != nil {
        return nil, errmsg.ERROR_CATE_NOT_EXIST, 0
    }

    // 查询文章列表
    err = db.Select("id, user_id, title, `desc`, created_at, img, comment_count, read_count, like_count").
        Limit(pageSize).
        Offset((pageNum-1)*pageSize).
        Where("cid = ?", id).
        Find(&cateArtList).Error
    if err != nil {
        // fmt.Println("Error:", err)
        return nil, errmsg.ERROR_CATE_NOT_EXIST, 0
    }

    var result []gin.H
    for _, article := range cateArtList {
        username, _ := GetUserName(article.UserID)
        user, err := GetUserFromName(username)
        if err != errmsg.SUCCESS {
            fmt.Println("Error getting user:", err)
            continue
        }

        imgArray := strings.Split(article.Img, ",")

        // 使用 gin.H 将用户信息拼接到文章中
        result = append(result, gin.H{
            "id":         article.ID,
            "userid":     article.UserID,
            "title":      article.Title,
            "desc":       article.Desc,
            "createTime": article.CreatedAt,
            "imgs":       imgArray,
            "commentNum": article.CommentCount,
            "readNum":    article.ReadCount,
            "likeNum":    article.LikeCount,
            "user": gin.H{
                "id":       user.ID,
                "username": user.Username,
                "avatar":   user.Avatar,
            },
        })
    }

    return result, errmsg.SUCCESS, total
}

// GetArtInfo 查询单个文章
func GetArtInfo(id int) (gin.H, int) {
    var art Article
    // err = db.Where("id = ?", id).Preload("Category").First(&art).Error
    err = db.Where("id = ?", id).First(&art).Error
    db.Model(&art).Where("id = ?", id).UpdateColumn("read_count", gorm.Expr("read_count + ?", 1))

    username, _ := GetUserName(art.UserID)
    imgArray := strings.Split(art.Img, ",")
    result := gin.H{
        "id":          art.ID,
        "title":       art.Title,
        "content":     art.Content,
        "img":         imgArray,
        "username":    username,
        "cid":         art.Cid,
        "commentNum":  art.CommentCount,
        "readNum":     art.ReadCount,
        "likeNum":     art.LikeCount,
        "createTime":  art.CreatedAt,
        "category_id": art.Cid,
    }
    if err != nil {
        fmt.Println(id)
        fmt.Println("Error:", err)
        return result, errmsg.ERROR_ART_NOT_EXIST
    }
    
    return result, errmsg.SUCCESS
}

// GetArt 查询文章列表
func GetArt(pageSize int, pageNum int) ([]Article, int, int64) {
    var articleList []Article
    var err error
    var total int64

    err = db.Select("article.id, title, img, created_at, updated_at, `desc`, comment_count, read_count, category.name").
        Limit(pageSize).Offset((pageNum - 1) * pageSize).Order("Created_At DESC").Joins("Category").Find(&articleList).Error
    // 单独计数
    db.Model(&articleList).Count(&total)
    if err != nil {
        return nil, errmsg.ERROR, 0
    }
    return articleList, errmsg.SUCCESS, total

}

// SearchArticle 搜索文章标题
// func SearchArticle(title string, pageSize int, pageNum int) ([]Article, int, int64) {
//     var articleList []Article
//     var err error
//     var total int64
//     err = db.Select("article.id,title, img, created_at, updated_at, `desc`, comment_count, read_count, Category.name").Order("Created_At DESC").Joins("Category").Where("title LIKE ?",
//         title+"%",
//     ).Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&articleList).Error
//     //单独计数
//     db.Model(&articleList).Where("title LIKE ?",
//         title+"%",
//     ).Count(&total)

//     if err != nil {
//         return nil, errmsg.ERROR, 0
//     }
//     return articleList, errmsg.SUCCESS, total
// }

// EditArt 编辑文章
func EditArt(id int, data *Article) int {
    var art Article
    var maps = make(map[string]interface{})
    maps["title"] = data.Title
    maps["cid"] = data.Cid
    maps["desc"] = data.Desc
    maps["content"] = data.Content
    maps["img"] = data.Img

    err = db.Model(&art).Where("id = ? ", id).Updates(&maps).Error
    if err != nil {
        return errmsg.ERROR
    }
    return errmsg.SUCCESS
}

// DeleteArt 删除文章
func DeleteArt(id int) int {
    var art Article
    err = db.Where("id = ? ", id).Delete(&art).Error
    if err != nil {
        return errmsg.ERROR
    }
    return errmsg.SUCCESS
}

// SearchArticleByTitleAndContent 搜索文章标题和内容
func SearchArticleByTitleAndContent(keyword string, pageSize int, pageNum int) ([]gin.H, int, int64) {
    var articleList []Article
    var err error
    var total int64

    // 构建查询条件
    query := db.Select("id, user_id, img, title, created_at, comment_count, like_count").
        Order("Created_At DESC").
        // Joins("Category").    // 关联分类
        Where("title LIKE ? OR content LIKE ?", "%"+keyword+"%", "%"+keyword+"%")
        // Limit(pageSize).
        // Offset((pageNum - 1) * pageSize)    // 限制单次查找数量

    // 执行查询
    err = query.Find(&articleList).Error
    if err != nil {
        // fmt.Println(err)
        return nil, errmsg.ERROR, 0
    }

    // 计算总条数
    err = db.Model(&Article{}).Where("title LIKE ? OR content LIKE ?", "%"+keyword+"%", "%"+keyword+"%").Count(&total).Error
    if err != nil {
        // fmt.Println(err)
        return nil, errmsg.ERROR, 0
    }

    var result []gin.H
    for _, articleList := range articleList {
        username, _ := GetUserName(articleList.UserID)
        user, _ := GetUserFromName(username)

        imgArray := strings.Split(articleList.Img, ",")
        result = append(result, gin.H{
            "id":         articleList.ID,
            "commentNum": articleList.CommentCount,
            "likeNum":    articleList.LikeCount,
            "title":      articleList.Title,
            "imgs":       imgArray,
            "createTime": articleList.CreatedAt,
            "user": gin.H{
                "id":       user.ID,
                "username": user.Username,
                "avatar":   user.Avatar,
            },
        })
    }
    return result, errmsg.SUCCESS, total
}
